import { WarehouseService } from './../../services/warehouse.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, Validators } from '@angular/forms';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { RepositoryService } from '../../services/repository.service';
import { map } from 'rxjs/operators';
import { Warehouse } from '../../services/warehouse.service';
import { kebabCase } from 'lodash';

@Component({
  selector: 'm-warehouse',
  templateUrl: './warehouse.component.html',
  styleUrls: ['./warehouse.component.scss']
})
export class WarehouseComponent implements OnInit {
	constructor(
		private route: ActivatedRoute,
		private router: Router,
		private fb: FormBuilder,
		private toaster: ToasterService,
    private service: RepositoryService,
    private warehouse: WarehouseService
	) {}

	repoForm = this.fb.group({
		DeepinAppStoreUrl: ['', Validators.required],
    DeepinAppStoreSourceList: [['']],
    DeepinAppStoreIconUrl: [''],
    DeepinAppStoreBackgroundUrl: ['']

	});
	// context$ = this.repoForm.valueChanges.pipe(map(value => this.preview(value)));

	async ngOnInit() {
    const resp = await this.warehouse.getAppStore();
    const appStoreConfigs: Partial<Warehouse> = resp['message'];
    const formData = this.getFormData(appStoreConfigs);
    console.log('formData', formData);
    this.repoForm.patchValue(formData);

  }

  getFormData(appStoreConfigs) {
    const data = {}
    appStoreConfigs.forEach(config => {
      if (config.sys_key === 'DeepinAppStoreSourceList') {
        console.log(config.sys_value);
        data[config.sys_key] = JSON.parse(config.sys_value)
      } else {
        data[config.sys_key] = config.sys_value;
      }
    });
    console.log('data', data);
    return data;
  }

  convertMetaData(formData) {
    const data = [];
    for (const key in formData) {
      const cell = {};
      if (Object.prototype.hasOwnProperty.call(formData, key)) {
        if (key === 'DeepinAppStoreSourceList') {
          cell['sys_value'] = JSON.stringify(formData[key]);
        } else {
          cell['sys_value'] = formData[key];
        }
        cell['sys_key'] = key;
      }
      data.push(cell);
    }
    return data;
  }

	async submit() {
		const value: Warehouse = this.repoForm.value;
    const data = this.convertMetaData(value);
    console.log('data', data, JSON.stringify({configs: data}));
    const formData = new FormData();
    formData.append('configs', JSON.stringify(data));
    console.log('JSON.stringify(data)', JSON.stringify(data));
    await this.warehouse.patchAppStore(formData);
		this.toaster.success('保存成功');
		setTimeout(() => {
      this.reload();
      this.repoForm.markAsUntouched();
		}, 500)
  }

	async sync() {
		await this.warehouse.sync();
		this.toaster.success('已同步');
	}

	reload() {
		this.router.navigated = false;
		this.router.navigate([], { queryParamsHandling: 'merge' });
	}
}
